import React, { useRef } from 'react'
import { Modal, Form, Input, message } from 'antd'
import { $put } from '@js/authRequest'
import { awaitWrap } from '@js/tool'

const { Item } = Form
const { TextArea } = Input

async function cancelRequest (id, remark) {
  const res = await $put('/api/vendor/flowinstance/cancelFlowInstance', {
    instanceid: id,
    cancelRemark: remark
  })
  if (res.status !== 1) {
    throw new Error(res.message)
  }
  return res.data
}

// 表单提交完成回调
async function finishHandle (d, instance = {}, hide = () => {}, refreshApprove = () => {}) {
  const h = message.loading('提交中')
  const [e] = await awaitWrap(cancelRequest(instance.id, d.remark))
  h()
  if (e) {
    return message.error(e.message)
  }
  hide()
  refreshApprove()
}

function Main ({ visible = false, instance = {}, hide = () => {}, refreshApprove = () => {} }) {
  const formRef = useRef(null)
  return (
    <Modal open={visible} title='删除呈批' onOk={() => formRef.current.submit()} onCancel={hide}>
      <Form ref={formRef} onFinish={d => finishHandle(d, instance, hide, refreshApprove)}>
        <Item label='原因' name='remark' rules={[{ required: true, message: '原因不能为空' }]}>
          <TextArea rows={3} />
        </Item>
      </Form>
    </Modal>
  )
}

export default Main
